package com.bookocean.domain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bookocean.application.common.RedisConstants;

import com.bookocean.controller.dto.DailyQuoteResultDto;
import com.bookocean.domain.repository.DailyQuoteRepository;
import com.bookocean.domain.service.DailyQuoteDomainService;
import com.bookocean.domain.utils.RedisUtils;
import com.bookocean.infrastructure.persistence.po.DailyQuotePO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 每日一句领域服务实现类
 *
 * @author BookOcean
 * @since 2024-01-01
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DailyQuoteDomainServiceImpl implements DailyQuoteDomainService {

    private final DailyQuoteRepository dailyQuoteRepository;
    private final RedisUtils redisUtils;

    @Override
    public DailyQuoteResultDto getDailyQuote(Long userId) {
        log.info("获取每日一句,用户信息为：{}", userId);
        Object object = redisUtils.get(RedisConstants.BOOK_OCEAN_DAILY_USER + userId);
        if (object != null) {
            DailyQuoteResultDto quoteDto = new DailyQuoteResultDto();
            BeanUtil.copyProperties(object, quoteDto);
            if (ObjectUtil.isNotEmpty(quoteDto)){
                return quoteDto;
            }
        }
        // 从数据库获取今日的每日一句
        Long count = getDailyQuoteCount();
        DailyQuotePO dailyQuote = dailyQuoteRepository.findByQuizId(count);
        if (dailyQuote == null) {
            // 如果没有找到，返回默认数据
            return getDefaultDailyQuote();
        }
        // 转换为 DTO
        DailyQuoteResultDto dto = new DailyQuoteResultDto();
        BeanUtil.copyProperties(dailyQuote, dto);
        return dto;
    }

    private Long getDailyQuoteCount() {
        // 获取时安全转换，避免 ClassCastException
        Object countObj = redisUtils.get(RedisConstants.BOOK_OCEAN_DAILY_COUNT);
        Long count = null;
        if (countObj != null) {
            if (countObj instanceof String) {
                count = Long.valueOf((String) countObj);
            } else if (countObj instanceof Number) {
                count = ((Number) countObj).longValue();
            }
        }
        
        if (count == null) {
            count = dailyQuoteRepository.getCount();
            redisUtils.set(RedisConstants.BOOK_OCEAN_DAILY_COUNT, String.valueOf(count), 2 * 60 * 60, TimeUnit.SECONDS);
        }
        // 生成一个0到count 的随机数
        return (long) (Math.random() * count);
    }

    @Override
    public DailyQuoteResultDto submitAnswer(Long quizId, String userId, String answer) {
        // 获取今日题目
        DailyQuotePO dailyQuote = dailyQuoteRepository.findByQuizId(quizId);
        // 判断答案是否正确
        boolean isCorrect = dailyQuote.getBookTitle().equals(answer.trim());
        DailyQuoteResultDto result = new DailyQuoteResultDto();
        result.setCorrect(isCorrect);
        if (!isCorrect){
            return result;
        }
        // 构建返回结果
        result.setSubmittedBy(dailyQuote.getSubmittedBy());
        result.setSubmittedAt(dailyQuote.getSubmittedAt());
        result.setBookTitle(dailyQuote.getBookTitle());
        result.setAuthor(dailyQuote.getAuthor());
        result.setMaxLength(dailyQuote.getMaxLength());
        result.setId(dailyQuote.getId());
        result.setContent(dailyQuote.getContent());
        result.setCorrect(true);
        redisUtils.set(RedisConstants.BOOK_OCEAN_DAILY_USER + userId, result, 24 * 60 * 60, TimeUnit.SECONDS);
        return result;
    }

    /**
     * 获取默认每日一句
     */
    private DailyQuoteResultDto getDefaultDailyQuote() {
        DailyQuoteResultDto dto = new DailyQuoteResultDto();
        dto.setId(1L);
        dto.setContent("人生若只如初见，何事秋风悲画扇。等闲变却故人心，却道故人心易变。");
        dto.setBookTitle("纳兰词");
        dto.setAuthor("纳兰性德");
        dto.setSubmittedBy("简语");
        dto.setSubmittedAt(LocalDateTime.now());
        dto.setMaxLength(180);
        return dto;
    }

}
